package com.haiyou.common.util.yml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Map;

import org.yaml.snakeyaml.Yaml;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.Maps;

import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: yml 读取工具类
 * @author xingyuan
 * @date 2022年9月2日 下午2:53:46
 */
@Slf4j
public class YmlUtils {

	
	/**
	 * 读取 yml 读取为 key: node1.node2  value:value
	 * @param path
	 * @return
	 */
	public static Map<String, Object> readYmlFile(String path){
		
		Map<String, Object> maps = Maps.newHashMap();
		Yaml yaml = new Yaml();
		
		File file = new File(path);
		try {
			@Cleanup
			FileInputStream fileInputStream = new FileInputStream(file);
			Object yml = yaml.load(fileInputStream);
			iterateNode(JSONObject.parseObject(JSONObject.toJSONString(yml)),"",maps);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return maps;
		}
		
		return maps;
	}

	/**
	 * 遍历所有子节点
	 * @param jb
	 * @param parentNodeKey
	 * @param maps
	 */
	public static void iterateNode(JSONObject jb,String parentNodeKey,Map<String, Object> maps) {
		
		  for(String key : jb.keySet()) {
	            if(jb.get(key) instanceof JSONObject){
	                JSONObject childJb = JSONObject.parseObject(String.valueOf(jb.get(key)));
	                if(!org.springframework.util.StringUtils.hasLength(parentNodeKey)) {
	                	iterateNode(childJb,key,maps);
	                }else {
	                	iterateNode(childJb,parentNodeKey +"."+ key,maps);
	                }
	            }else{
	            	maps.put(parentNodeKey +"."+key, jb.get(key));
	            }
	        }
	}
	
}



